package com.shanghaionstar.remote.share;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.map.util.ToastUtil;
import com.onstar.cn.vehicle.response.AuthorizedSubscriberResponse;
import com.onstar.cn.weight.ProgressLayout;
import com.onstar.cn.weight.wheel.adapters.AbstractWheelTextAdapter;
import com.onstar.cn.weight.wheel.views.OnWheelChangedListener;
import com.onstar.cn.weight.wheel.views.WheelView;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.R;
import com.shanghaionstar.remote.share.presenters.AuthorizeEditPresenter;
import com.shanghaionstar.remote.share.views.IShareRemoteListView;
import com.shanghaionstar.user.CircleImageView;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.weight.TopLayout;

import java.util.ArrayList;

import static java.util.Arrays.asList;

/**
 * Created by 11203rl on 2017/5/18.
 */

public class ShareTimeEditFrg extends BaseFragment implements View.OnClickListener, IShareRemoteListView {
    @FindViewById(R.id.update_btn)
    private Button mUpdateBtn;
    @FindViewById(R.id.time_wv)
    private WheelView mTimeWv;
    @FindViewById(R.id.face_iv)
    private CircleImageView mFaceIv;
    @FindViewById(R.id.edit_rl)
    private RelativeLayout mEditRl;
    @FindViewById(R.id.top_layout)
    private TopLayout mTopLayout;
    @FindViewById(R.id.share_pl)
    private ProgressLayout mSharePl;

    String[] selectTimes;
    CalendarTextAdapter mTimeAdapter;
    private String selectTime;
    private final int maxTextSize = 24;
    private final int minTextSize = 14;

    private int currItem = -1;

    AuthorizedSubscriberResponse request;
    private AuthorizeEditPresenter presenter;

    @Override
    public int getLayoutId() {
        return R.layout.remote_edit_time;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (isFirstLoad()) {
            Bundle bun = getArguments();
            request = (AuthorizedSubscriberResponse) bun.getSerializable("authorize");
            presenter = new AuthorizeEditPresenter(baseActivity.getScheduler(), baseActivity);
            presenter.setView(this);
            selectTimes = getResources().getStringArray(R.array.authorize_time_items);
            selectTime = selectTimes[1];
            currItem = 1;
            mTimeWv.setVisibleItems(4);
            mTimeWv.setCyclic(true);
            mTimeWv.setShadowsColors(SHADOWS_COLORS);
            mTimeWv.setCenterDrawable(getResources().getDrawable(R.drawable.layer_list));
            mTimeWv.invalidate();
            mTimeAdapter = new CalendarTextAdapter(getActivity(), new ArrayList<String>(asList(selectTimes)), 1, mTimeWv, R.layout.authorize_edit_item);
            mTimeWv.setViewAdapter(mTimeAdapter);

            String limit = request.getLimit();
            String authorize = request.getAuthorizeStatus();
            boolean isAuthorize = authorize.equalsIgnoreCase("1");
            if (!isAuthorize) {
                mTimeWv.setCurrentItem(1);
            } else {
                if (limit.equalsIgnoreCase(0 + "")) {
                    mTimeWv.setCurrentItem(0);
                } else if ((24 + "").equalsIgnoreCase(limit)) {
                    mTimeWv.setCurrentItem(1);
                } else if ((7 * 24 + "").equalsIgnoreCase(limit)) {
                    mTimeWv.setCurrentItem(2);
                } else {
                    mTimeWv.setCurrentItem(3);
                }
            }

            mTimeWv.addChangingListener(new OnWheelChangedListener() {

                @Override
                public void onChanged(WheelView wheel, int oldValue, int newValue) {
                    // TODO Auto-generated method stub
//                    String currentText = (String) mTimeAdapter.getItemText(wheel.getCurrentItem());
//                    selectTime = currentText;
                    currItem = wheel.getCurrentItem();
                    setTextviewSize(wheel, mTimeAdapter);
                }
            });

            mTopLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    back();
                }
            });

            ImageLoader.getInstance().displayImage(request.getFaceUrl(), mFaceIv, OnstarApplication.getOptions(true, false, R.drawable.authorize_head));
        }
    }

    /**
     * 设置字体大小
     *
     * @param adapter
     */
    private void setTextviewSize(WheelView wheel, CalendarTextAdapter adapter) {
        ArrayList<TextView> arrayList = adapter.getTestViews();
        for (int i = 0; i < arrayList.size(); i++) {
            TextView view = arrayList.get(i);
//            view.setTextColor(getResources().getColor(R.color.blackColor));
            if (((Integer) view.getTag()) == wheel.getCurrentItem()) {
                view.setTextSize(maxTextSize);
            } else if (Math.abs((Integer) view.getTag() - wheel.getCurrentItem()) == 1
                    || adapter.list.size() - Math.abs((Integer) view.getTag() - wheel.getCurrentItem()) == 1) {
                view.setTextSize((maxTextSize + minTextSize) / 2.0f);
            } else if (Math.abs((Integer) view.getTag() - wheel.getCurrentItem()) == 2
                    || adapter.list.size() - Math.abs((Integer) view.getTag() - wheel.getCurrentItem()) == 2) {
                view.setTextSize(minTextSize);
            } else {
                view.setTextSize(minTextSize);
            }
        }
    }

    @OnClick({R.id.update_btn})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.update_btn:
                updateAuthorizeInfo();
                break;
        }
    }

//    public void setRotate(boolean isRotate) {
//        Bitmap bitmap = ((BitmapDrawable) getResources().getDrawable(R.drawable.authorize_edit_arrow)).getBitmap();
//        if (isRotate) {
//            // 设置旋转角度
//            Matrix matrix = new Matrix();
//            matrix.setRotate(isRotate ? 90 : 0);
//            // 重新绘制Bitmap
//            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
//        }
//        mTurnIv.setImageBitmap(bitmap);
//    }

//    public void showWheelView(boolean isShow) {
//        mTimeWv.setVisibility(isShow ? View.VISIBLE : View.GONE);
//        mEditRl.setVisibility(isShow ? View.VISIBLE : View.GONE);
//        setRotate(isShow);
//    }

    public void updateAuthorizeInfo() {
        switch (currItem) {
            case 0:
                request.setLimit("0");
                break;
            case 1:
                request.setLimit("24");
                break;
            case 2:
                request.setLimit(7 * 24 + "");
                break;
            case 3:
                request.setLimit(30 * 24 + "");
                break;
        }
        request.setAuthorizeStatus("1");
        presenter.setAuthorizedStatus(request);
    }

    @Override
    public void setLoading(boolean isLoading) {
        mSharePl.setVisibility(isLoading ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onResponseError(OnStarException e) {
        AlertDialogUtil.showDialogByOnstarException(baseActivity, e);
    }

    @Override
    public void onReponseSuccess(Object object) {
        back();
        RxBus.getDefault().post(ShareRoleListFrg.UPDATE_SUC, "success");
    }

    @Override
    public Activity onActivity() {
        return getActivity();
    }

    private int[] SHADOWS_COLORS = new int[]{0xffffff, 0xffffff, 0xffffff};

    @Override
    public void onRemoteShareSetFailed(OnStarException e) {
        ToastUtil.showShort(OnstarApplication.getApplication(),R.string.remote_share_set_failed);
    }

    private class CalendarTextAdapter extends AbstractWheelTextAdapter {
        ArrayList<String> list;
        WheelView wheelView;

        protected CalendarTextAdapter(Context context, ArrayList<String> list, int currentItem, WheelView wheelView,
                                      int layoutId) {
            super(context, layoutId, NO_RESOURCE, currentItem, maxTextSize, minTextSize);
            this.list = list;
            this.wheelView = wheelView;
            setItemTextResource(R.id.time_tv);
        }

        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            View view = super.getItem(index, cachedView, parent);
            setTextviewSize(wheelView, this);
            return view;
        }

        @Override
        public int getItemsCount() {
            return list.size();
        }

        @Override
        protected CharSequence getItemText(int index) {
            return list.get(index) + "";
        }
    }


}
